package bangry.chat.server.control;

import java.util.Hashtable;
import java.util.Vector;

public class ChatManager {
	
	static ChatManager instance;

	// 접속한 모든 클라이언트를 관리하기 위한 Vector
	private Vector<ConnectionChatClient> connectedClientList;
		
	
	
	// 채팅방 관리를 위한 Map <방이름:ChatRoom> 형식
	private Hashtable<String, ChatRoom> roomList;
	

	private ChatManager() {
		connectedClientList = new Vector<ConnectionChatClient>(50, 2);
		roomList = new Hashtable<String, ChatRoom>();
		

	}

	public static ChatManager getInstance() {
		if (instance == null) {
			instance = new ChatManager();
		}
		return instance;
	}
	
	// 접속한 클라이언트 등록 
	public void registChatClient(ConnectionChatClient client){
		connectedClientList.addElement(client);
		System.out.println("접속 클라이언트 수: " + connectedClientList.size());
	}
	
	
	// 접속 종료 클라이언트 제거 
	public void removeChatClient(ConnectionChatClient client){
		connectedClientList.remove(client);
		System.out.println("제거후 접속 클라이언트 수: " + connectedClientList.size());
	}
	
	
	// 방개설
	public void makeChatRoom(String roomName, String captin){
		makeChatRoom(roomName, 10, captin, true);
	}
	
	
	public void makeChatRoom(String roomName, int roomSize, String captin, boolean open){
		ChatRoom openRoom = new ChatRoom(roomName, roomSize, captin, open);
		roomList.put(roomName, openRoom);
	}
	
	// 방이동
	public void moveChatRoom(String roomName,  ConnectionChatClient client){
		ChatRoom room = searchChatRoom(roomName);
		System.err.println(client.getNickName());
		room.enterChatRoom(client.getNickName(), client);
	}
	
	
	// 방삭제
	public void removeChatRoom(String roomName){
		roomList.remove(roomName);
	}
	
	// 방검색
	public ChatRoom searchChatRoom(String roomName){		
		return roomList.get(roomName);
	}
	
	// 방리스트
	public String getChatRoomList(){
		StringBuffer sb = new StringBuffer();
		for(ChatRoom room : roomList.values()){
			sb.append( room.getRoomName() + "/");
		}
		return sb.toString(); 
	}
	
	// 쪽지 전송
	public void sendMemo(String sender, String receiver, String memo) {
		searchChatClient(receiver).sendMessage("2100||" + sender + "||" + receiver + "||" + memo);		
	}	
		
	
	
	// 연결되어 있는 클라이언트 검색
	private ConnectionChatClient searchChatClient(String nickName){
		for(ConnectionChatClient client : connectedClientList){
			if(client.getNickName().equals(nickName)){
				return client;
			}
		}
		return null;
		
		
	}

}
